import { ref } from 'vue'

export interface FilterConfig {
  type: string
  placeholder: string
  multiple?: boolean
  min?: number
  max?: number
  marks?: Record<number, string>
  unit?: string
  options?: Array<{
    label: string
    value: string | number
  }>
}

export interface FilterCondition {
  field: string
  operator: string
  value: any
}

export interface FilterResult {
  field: string
  include: FilterCondition[]
  exclude: FilterCondition[]
  filterConfig: FilterConfig
}

export function useAdvancedFilter() {
  // 存储所有高级筛选组件的引用
  const advancedFilterRefs = ref<Record<string, any>>({})

  // 筛选相关状态
  const activeFilters = ref<Record<string, boolean>>({})

  // 打开高级筛选弹窗
  const openAdvancedFilter = (prop: string) => {
    const filterRef = advancedFilterRefs.value[prop]
    if (filterRef && typeof filterRef.openDialog === 'function') {
      filterRef.openDialog()
    }
  }

  // 筛选条件记录
  const queryFilters = ref({})
  // 表格筛选条件记录
  const tableFilters = ref({})

  // 应用筛选
  const applyFilter = (filters: FilterResult) => {
    // 更新筛选状态
    activeFilters.value[filters.field] = !!(
      filters.exclude?.some((item) => item.value || item.value === 0) ||
      filters.include?.some((item) => item.value || item.value === 0)
    )
  }

  // 清除筛选
  const clearFilter = (prop: string) => {
    activeFilters.value[prop] = false
  }

  // 检查筛选是否激活
  const isFilterActive = (prop: string): boolean => {
    return activeFilters.value[prop]
  }

  // 处理高级筛选结果
  const handleAdvancedFilterChange = (filters: FilterResult, sourceToTable = false) => {
    if (sourceToTable) {
      // 这是表头筛选结果记录：额外修改筛选图标状态
      applyFilter(filters)
      tableFilters.value[filters.field] = filters
    } else {
      // 这是查询筛选结果记录
      queryFilters.value[filters.field] = filters
    }
    return filters
  }
  return {
    queryFilters,
    tableFilters,
    advancedFilterRefs,
    activeFilters,
    openAdvancedFilter,
    applyFilter,
    clearFilter,
    isFilterActive,
    handleAdvancedFilterChange
  }
}
